package net.area80.components
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import net.area80.components.skin.ABScrollbarSkin;
	import net.area80.utils.DrawingUtils;
	
	import org.osflash.signals.Signal;
	
	
	public class UITableVScrollList extends Sprite
	{
		private var listHeight:uint;
		private var listWidth:uint;
		private var itemHeight:uint;
		private var itemWidth:uint;

		private var scroll:VScrollbar;
		private var skin:ABScrollbarSkin;
		private var masking:Sprite;
		private var container:Sprite;
		private var itemList:Vector.<UIListItem>;
		
		private var row:uint;
		private var col:uint;
		
		public function UITableVScrollList (itemWidth:uint, itemHeight:uint,col:uint,row:uint, skin:ABScrollbarSkin, snap:Boolean=false, forceListWidth:uint=0, forceListHeight:uint = 0)
		{
			super();
			
			this.row = row;
			this.col = col;
			
			this.itemHeight = itemHeight;
			this.itemWidth = itemWidth;
			
			this.listHeight = (forceListHeight!=0) ? forceListHeight : itemHeight*row;
			this.listWidth =  (forceListWidth!=0) ? forceListWidth : itemWidth*col;
			this.skin = skin;
			
			container = new Sprite();
			addChild(container);
			
			scroll = new VScrollbar(skin,container,listHeight,((snap) ? itemHeight : 1 ));
			addChild(scroll);
			
			scroll.x = listWidth;
			scroll.height = listHeight;
		
			container.cacheAsBitmap = true;
			masking = DrawingUtils.getRectSprite(listWidth,listHeight);
			masking.cacheAsBitmap = true;
			addChild(masking);
			container.mask = masking;
			
			addEventListener(Event.REMOVED_FROM_STAGE, dispose);
			//addEventListener(Event.ENTER_FRAME, positionUpdate);
			
			
		}
		private function dispose (e:Event):void {
			//removeEventListener(Event.ENTER_FRAME, positionUpdate);
		}
		public function get length ():uint {
			return (itemList) ? itemList.length : 0;
		}
		public function getItemAt (id:uint):UIListItem {
			return (itemList) ?  itemList[id] : null;
		}
		public function getItemList ():Vector.<UIListItem> {
			return itemList;
		}
		public function addItem (u:UIListItem):void {
			if(!itemList) itemList = new Vector.<UIListItem>;
			u.init(this);
			u.cacheAsBitmap = true;
			container.addChild(u);
			itemList.push(u);
			positionItem();
		}
		private function positionItem ():void {
			var count:uint = 0;
			if(itemList) {
				for(var i:uint =0;i<itemList.length;i++) {
					if(itemList[i].visible) {
						itemList[i].x = itemWidth*(count%col);
						itemList[i].y = itemHeight*Math.floor(count/col);
						count++;
					}
				}
			}
			scroll.updateDisplay();
			
		}
		private function positionUpdate (e:Event):void {
			positionItem();
			
		}
		
	}
}